<template>
  <div class="search">
    <!-- 搜索组件一级路由   $router.back()返回上一个页面-->
    <van-nav-bar
      left-arrow
      title="搜索中心"
      @click-left="$router.back()">
    </van-nav-bar>

    <!-- https://youzan.github.io/vant/#/zh-CN/search -->
    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
      @input="getSuggestions"
    >
      <template #action>
        <div @click='clickBtn'>搜索</div>
      </template>
    </van-search>

    <!-- 联想建议 -->
    <van-cell-group v-if='keyword'>
      <van-cell  icon="search" v-for='(str,index) in renderSuggestions' :key='index'>
        <span v-html="str" @click='clickSuggestion(index)'></span>
      </van-cell>
    </van-cell-group>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <van-cell-group v-else>
  <van-cell title="历史记录">
  </van-cell>
  <van-cell v-for="item in history" :key="item" :title="item" @click='clickHistory(item)'>
    <van-icon name="close" @click.stop='delHistory(item)' />
  </van-cell>
</van-cell-group>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import { reqGetSuggestions } from '@/api/search'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Search',
  data () {
    return {
      keyword: '', // 搜索关键字
      suggestList: [],
      timerId: '',
      history: JSON.parse(localStorage.getItem('History')) || []
    }
  },
  computed: {
    // 展示的是计算属性的元素 发起请求的是原数组
    renderSuggestions () {
      const reg = new RegExp(this.keyword, 'gi')
      return this.suggestList.map(item => {
        return item.replace(reg, (val) => {
          return `<span style="color:red">${val}</span>`
        })
      })
    }
  },
  methods: {
    async getSuggestions () {
      clearTimeout(this.timerId)
      this.timerId = setTimeout(async () => {
        if (!this.keyword) {
          this.suggestList = []
          return
        }
        const { data: { data: { options } } } = await reqGetSuggestions(this.keyword)
        this.suggestList = options
      }, 300)
    },
    // 点击联想
    clickSuggestion (index) {
      this.addHistory(this.suggestList[index])
    },
    // 点击搜索按钮
    clickBtn () {
      if (!this.keyword) return
      this.addHistory(this.keyword)
    },
    // 删除历史记录
    delHistory (index) {
      this.history.splice(index, 1)
      localStorage.setItem('History', JSON.stringify(this.history))
    },
    // 点击历史记录跳转更新视图
    clickHistory (value) {
      this.addHistory(value)
    },
    // 追加记录
    addHistory (str) {
      this.history.unshift(str)
      this.history = [...new Set(this.history)]
      localStorage.setItem('History', JSON.stringify(this.history))
      this.$router.push({
        path: '/searchResult',
        query: {
          keyword: str
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 控制头部导航栏的通用样式
::v-deep .van-nav-bar {
  background-color: #3196fa;
  .van-nav-bar__title {
    color: white;
  }
  .van-icon {
    color: white;
  }
}
</style>
